package com.hs.libs.web;

import com.hs.libs.BaseUITasks;
import com.hs.utils.Tools;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

/**
 * Web UI 自动化测试任务
 */
public class WebUITasks extends BaseUITasks {
    private static Logger logger = Logger.getLogger(WebUITasks.class);
    static long maxWait = 30; //seconds

    public static void inputText(String txt, WebDriver driver) throws Exception {
        WebElement searchInput = findElementByXpath("//input[@name='wd' and @id='kw']", driver);
        searchInput.sendKeys(txt);
        logger.info("输入搜索关键词：" + txt);
    }

    public static void clickSearchBtn(WebDriver driver) throws Exception {
        WebElement searchBtn = findElementByXpath("//input[@type='submit' and @id='su']", driver);
        searchBtn.click();
        logger.info("单击搜索按钮");
    }

    public static void searchKeyword(String keyword, WebDriver driver) throws Exception {
        inputText(keyword, driver);
        clickSearchBtn(driver);

        //Wait until the keyword shown on the title or timeout
        long start = System.currentTimeMillis();
        long now = System.currentTimeMillis();
        boolean ret = false;
        while (((now - start) < maxWait * 1000) && !ret) {
            Tools.wait(1);
            String browserTitle = driver.getTitle();
            ret = browserTitle.contains(keyword) || browserTitle.contains("安全验证");
            now = System.currentTimeMillis();
        }
    }
}
